import { createSlice } from '@reduxjs/toolkit';
import { RootState } from '../store';

export interface IMember {
    name: string
    email: string
    permissions: string
}

export interface IOrganization {
    id: number
    name: string
    memberList: Array<IMember>
}

interface IState {
    list: Array<IOrganization>
}

const initialState: IState = {
    list: [
        {
            id: 1,
            name: 'dataReachable Pty Ltd',
            memberList: [
                {
                    name: 'James',
                    email: 'James@163.com',
                    permissions: 'owner',
                },
                {
                    name: 'Paul',
                    email: 'Paul@163.com',
                    permissions: 'lv1',
                }
            ],
        },
    ],
}


export const counterSlice = createSlice({
    name: 'global',
    initialState: initialState,
    reducers: {
        addOrganization(state, { payload }) {
            state.list = [...state.list, payload]
        },
        addMember(state, {payload}) {
            state.list.find((item: IOrganization) => item.id === payload.id)?.memberList.push(payload.member)
        }
    },
});

// 导出actions
export const { addOrganization, addMember } = counterSlice.actions;

export const list = (state: RootState) => state.global
// 内置了thunk插件，可以直接处理异步请求
export const asyncIncrement = (payload: any) => (dispatch: (arg0: { payload: any; type: string; }) => void) => {
    setTimeout(() => {
        dispatch(addOrganization(payload));
    }, 2000);
};

export default counterSlice.reducer;